import requests
import logging
import json
from Scripts import template
from Scripts.headers import config, log_format, feishu_header, feishu_header_select

logging.basicConfig(level=logging.WARNING,
                    format=log_format)


# 发送消息给指定用户
def send_mess(action_type, user_json_input):
    mess_url = "https://open.feishu.cn/open-apis/message/v4/send/"  # 请求地址
    header = feishu_header()

    post_data_entry_group = dict()
    post_data_entry_group["chat_id"] = config.get("feishu", 'Entry_chat')
    post_data_entry_group["msg_type"] = "interactive"

    def mess_json(mess_type='text',
                  id_type='chat_id',
                  send_id=config.get('feishu', 'sys_chat'),
                  mess_num=None):

        if action_type == "create_true":
            if mess_type == "card":
                content = template.entry_success_card(user_json_input["name_pinyin"], user_json_input["password"])
            else:
                content = template.text_mess(user_json_input["name_pinyin"],
                                             user_json_input["password"],
                                             user_json_input['user_id'],
                                             action_type,
                                             mess_num=mess_num)

        elif action_type == 'create_false':
            if mess_type == 'card':
                content = template.entry_false_card(user_json_input["name_pinyin"])
            else:
                content = template.entry_false_card(user_json_input["name_pinyin"])

        elif action_type == 'change_password':
            if mess_type == 'card':
                content = template.change_password_card(user_json_input["name_pinyin"], user_json_input["password"])
            else:
                content = template.change_password_text(user_json_input["name_pinyin"], user_json_input["password"])

        elif action_type == 'disable_user':
            if mess_type == 'card':
                content = template.text_mess(user_json_input["name_pinyin"],
                                             user_json_input["password"],
                                             user_json_input['user_id'],
                                             action_type)
            else:
                content = template.text_mess(user_json_input["name_pinyin"],
                                             user_json_input["password"],
                                             user_json_input['user_id'],
                                             action_type)
        elif action_type == 'select_have':
            content = template.text_mess(user_name=user_json_input["en_name"],
                                         user_id=user_json_input['user_id'],
                                         action_type=action_type)

        elif action_type == 'select_have_not':
            content = template.text_mess(user_name=user_json_input["en_name"],
                                         user_id=user_json_input['user_id'],
                                         action_type=action_type)

        else:
            return False

        post_json = dict()
        post_json[id_type] = send_id
        if mess_type == "card":
            # 卡片消息
            post_json["msg_type"] = "interactive"
            post_json["card"] = content

        elif mess_type == "text":
            post_json["msg_type"] = "text"
            post_json["content"] = {"text": content}
        return post_json

    if action_type == "create_true":
        # 发送POST请求（员工个人）
        result_user = requests.post(mess_url,
                                    data=json.dumps(mess_json('card',
                                                              'user_id',
                                                              user_json_input['user_id']
                                                              )
                                                    ),
                                    headers=header)
        # 发送POST请求（系统组）
        result_sys = requests.post(mess_url,
                                   data=json.dumps(mess_json('text',
                                                             'chat_id',
                                                             config.get('feishu', 'sys_chat'),
                                                             mess_num=True
                                                             )
                                                   ),
                                   headers=header)
        # 发送POST请求（新人入职群）
        result_entry_group = requests.post(mess_url,
                                           data=json.dumps(mess_json('text',
                                                                     'chat_id',
                                                                     config.get('feishu', 'Entry_chat'),
                                                                     mess_num=False
                                                                     )
                                                           ),
                                           headers=header
                                           )
        logging.warning(f'发送创建成功消息：{result_user.text},{result_sys.text},{result_entry_group}')

    # 花名、花名拼音重复告警
    elif action_type == "create_false":
        data = json.dumps(mess_json('card',
                                    'chat_id',
                                    config.get('feishu', 'Entry_chat')))
        # 发送POST请求（新人入职群）
        result = requests.post(mess_url,
                               data=data,
                               headers=header)
        logging.warning(f'发送创建失败消息：{result.text}')

    # 修改密码
    elif action_type == "change_password":
        data = json.dumps(mess_json('text',
                                    'user_id',
                                    user_json_input['user_id'])
                          )

        # 发送POST请求（员工个人）
        result = requests.post(mess_url, data=data, headers=header)

        logging.warning(f'发送修改密码消息：{result.text}')

    elif action_type == "select_have":
        data = json.dumps(mess_json(mess_type='text',
                                    id_type=user_json_input['id_type'],
                                    send_id=user_json_input['re_id']))
        result = requests.post(mess_url, data=data, headers=feishu_header_select())

        logging.warning(f'发送查找消息：{result.text}')
    elif action_type == "select_have_not":
        data = json.dumps(mess_json(mess_type='text',
                                    id_type=user_json_input['id_type'],
                                    send_id=user_json_input['re_id']))
        result = requests.post(mess_url, data=data, headers=feishu_header_select())

        logging.warning(f'发送查找消息：{result.text}')

    elif action_type == "test":
        data = json.dumps(mess_json('text',
                                    'user_id',
                                    user_json_input['user_id'])
                          )
        # 发送POST请求（员工个人）
        result = requests.post(mess_url,
                               data=json.dumps(data),
                               headers=header)
        logging.warning(f'发送修改密码消息：{result.text}')

    elif action_type == 'disable_user':
        for post_chat in [config.get("feishu", 'Entry_chat'), config.get("feishu", 'sys_chat')]:
            data = mess_json('text',
                             'chat_id',
                             post_chat)
            # 发送POST请求，禁用用户操作
            del_result_group = requests.post(mess_url,
                                             data=json.dumps(data),
                                             headers=header)

            logging.warning(f'发送禁用用户消息：{del_result_group.text}')
